#include "sendfiledialog.h"
#include "ui_sendfiledialog.h"
#include "QFileDialog"
#include "QFileInfo"
#include "QMessageBox"

FileSender fileSender;

SendFileDialog::SendFileDialog(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SendFileDialog)
{
    ui->setupUi(this);
    ui->label_name->setText(myFriend.user_name);


    FileSender::connect(&fileSender, &FileSender::FileReceivedOk,[=](){
        QMessageBox::warning(this, "Warning!", "文件发送成功", QMessageBox::Yes);
        ui->toolButton_selectFile->setEnabled(true);
        fileName.clear();
        fileSize = 0;
        sendSize = 0;
        filePath = "";
        ui->label_message->setText("请选择文件");
    });

    FileSender::connect(&fileSender, &FileSender::FileReceivedError,[=](){
        QMessageBox::warning(this, "Warning!", "文件发送失败", QMessageBox::Yes);
    });

    FileSender::connect(&fileSender, &FileSender::UnknownReply,[=](){
        QMessageBox::warning(this, "Warning!", "未知错误", QMessageBox::Yes);
    });

    fileSender.connectToServer("127.0.0.1",8889);
}

SendFileDialog::~SendFileDialog()
{
    delete ui;
}

void SendFileDialog::on_toolButton_selectFile_clicked()
{
    filePath = QFileDialog::getOpenFileName(this,"选择文件","../");
    //若文件路径无效，则提示
    if(filePath.isEmpty())
    {
        QMessageBox::information(this,"Error: ",filePath+"文件路径无效");
        return;
    }
    fileName.clear();
    fileSize = 0;
    sendSize = 0;
    //获取文件信息
    QFileInfo info(filePath);
    fileName = info.fileName();
    fileSize = info.size();

    //指定文件的名称
    file.setFileName(filePath);
    //以只读方式打开文件
    bool isOK = file.open(QIODevice::ReadOnly);
    if(!isOK)
    {
        QMessageBox::information(this,"Error:","只读方式打开文件失败");
        return;
    }
    else
    {
        //提示打开文件路径
        ui->label_message->setText("选择文件成功："+fileName);
        ui->toolButton_selectFile->setEnabled(false);
    }
}


void SendFileDialog::on_toolButton_sendFile_clicked()
{

    FileInformation fileInformation;
    fileInformation.sender_id = me.id;
    fileInformation.receiver_id = myFriend.id;
    fileInformation.fileName = fileName;
    fileInformation.send_time = QTime::currentTime();

    fileSender.sendFile(fileInformation,filePath);
}

